import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'package:flutter_widgets_pc/resources/kq_theme_colors.dart';

import '../button/kq_head_button.dart';

/// 小诸葛右上角菜单
/// @author 高裕
class KqPopMenu<T extends KqPopMenuItemData> {
  static const String tag = "KqPopMenu";

  const KqPopMenu({
    Key? key,
    required this.data,
    this.menuSelectListener,
  });

  final List<T> data;

  final OnMenuSelectListener? menuSelectListener;

  /// 手动把菜单动态显示在屏幕上
  /// 这块功能已经集成到KqHeadBar，一般用不到这个了
  static void showKqMenu(BuildContext context, List<KqPopMenuItemData> data,
      OnMenuSelectListener? listener,{RelativeRect? rect}) {
    showMenu(
      context: context,
      position: rect ?? RelativeRect.fill,
      elevation: 3,
      color: KqThemeColors.bgWhite,
      items: buildItems(data, listener),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(5)),
      ),
    );
  }

  static List<PopupMenuItem<KqPopMenuItemData>> buildItems(
      List<KqPopMenuItemData> data, OnMenuSelectListener? listener) {
    int i = 0;
    for (KqPopMenuItemData e in data) {
      e.position = i;
      i++;
    }
    List<PopupMenuItem<KqPopMenuItemData>> list = [];
    for (KqPopMenuItemData e in data) {
      list.add(PopupMenuItem<KqPopMenuItemData>(
        value: e,
        height: 46,
        padding: const EdgeInsets.all(0),
        onTap: () {
          if (listener != null) {
            listener(e.position!, e.title, e);
          }
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(left: 8),
              width: 23,
              height: 23,
              child: Visibility(
                visible: e.imageUrl != null,
                child: Image.asset(e.imageUrl ?? ""),
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 8),
              child: Text(
                e.title,
                style: TextStyle(fontSize: 14, color: KqThemeColors.text26),
              ),
            )
          ],
        ),
      ));
    }
    return list;
  }
}

/// 菜单选中
typedef OnMenuSelectListener = void Function(
    int position, String title, KqPopMenuItemData entity);

